#include "datautils.h"

#include <QFile>
#include <QDebug>
#include <QTextStream>
#include <QRegularExpression>

// 图标映像
const QHash<QString, QString> IconUtils::ICON_MAP = {
    {"clear-day",           ":/type/images/weatherIcon/clear-day.png"},
    {"clear-night",         ":/type/images/weatherIcon/clear-night.png"},
    {"cloudy",              ":/type/images/weatherIcon/cloudy.png"},
    {"partly-cloudy-day",   ":/type/images/weatherIcon/partly-cloudy-day.png"},
    {"partly-cloudy-night", ":/type/images/weatherIcon/partly-cloudy-night.png"},
    {"rain",                ":/type/images/weatherIcon/rain.png"},
    {"snow",                ":/type/images/weatherIcon/snow.png"},
    {"wind",                ":/type/images/weatherIcon/wind.png"},
    {"fog",                 ":/type/images/weatherIcon/fog.png"}
};

// 日期转星期
QString DateUtils::dateToWeek(const QString &dateStr, const QString &sourceTimezone) {
    QDate date = QDate::fromString(dateStr, "yyyy-MM-dd");
    if (!date.isValid()) {
        qWarning() << "无效日期格式:" << dateStr;
        return "格式错误";
    }

    QTimeZone tz = QTimeZone(sourceTimezone.toUtf8());
    if (!tz.isValid()) {
        tz = QTimeZone::systemTimeZone();
        qWarning() << "使用默认时区:" << tz.id();
    }

    QDateTime dateTime(date.startOfDay(tz));

    static const QStringList weekDays = {
        "周日", "周一", "周二", "周三",
        "周四", "周五", "周六"
    };
    return weekDays.at(dateTime.date().dayOfWeek() % 7); // Qt的dayOfWeek()周一是1，周日是7
}

// 风向文字描述
QString WindUtils::degreeToDirection(double degree) {
    degree = fmod(degree + 360.0, 360.0);

    // 八个主方向定义
    const QVector<QString> directions = {
        "北风",   // 337.5-22.5
        "东北风",  // 22.5-67.5
        "东风",   // 67.5-112.5
        "东南风",  // 112.5-157.5
        "南风",   // 157.5-202.5
        "西南风",  // 202.5-247.5
        "西风",   // 247.5-292.5
        "西北风"   // 292.5-337.5
    };

    // 计算偏移量
    double adjusted = fmod(degree + 22.5, 360.0);
    return directions.at(static_cast<int>(adjusted / 45.0) % 8);
}

// 风速变风力等级
int WindUtils::getWindLevel(double windSpeedKmh) {
    static const QVector<QPair<double, int>> WIND_LEVELS = {
        {0.0,  0},
        {2.0,  1},
        {6.0,  2},
        {12.0, 3},
        {20.0, 4},
        {29.0, 5},
        {39.0, 6},
        {50.0, 7},
        {62.0, 8},
        {75.0, 9},
        {89.0, 10},
        {103.0,11},
        {118.0,12}
    };

    for (auto it = WIND_LEVELS.rbegin(); it != WIND_LEVELS.rend(); ++it) {
        if (windSpeedKmh >= it->first) {
            return it->second;
        }
    }
    return -1; // 异常值
}

// 加载城市拼音
CityConverter::CityData CityConverter::loadCityData() {
    CityData data;

    QFile file(":/city/pinyin.txt");
    if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        QTextStream in(&file);

        while (!in.atEnd()) {
            QString line = in.readLine().trimmed();
            if (line.isEmpty()) continue;

            QStringList parts = line.split(QRegularExpression("\\s+"), Qt::SkipEmptyParts);
            if (parts.size() >= 2) {
                QString chinese = parts[0];
                QString pinyin = parts[1].toLower(); // 统一小写存储
                data.cityToPinyin.insert(chinese, pinyin);
                data.pinyinToCity.insert(pinyin, chinese);
                data.pinyinSet.insert(pinyin);
            }

        }
        file.close();
    } else {
        qWarning() << "城市数据文件加载失败:" << file.errorString();
    }

    return data;
}

QString CityConverter::toPinyin(const QString &input) {
    static CityData cityData = loadCityData(); // 首次访问时加载数据
    QString processed = processInput(input);

    // 检查中文城市
    if (cityData.cityToPinyin.contains(processed)) {
        return cityData.cityToPinyin.value(processed);
    }

    QRegularExpression re("^[a-zA-Z\\s]+$");
    if (re.match(processed).hasMatch()) {
        return processed.toLower(); // 直接返回小写形式
    }

    // 无效输入返回空字符串
    qWarning() << "无效城市输入:" << input;
    return QString();
}

QString CityConverter::toChinese(const QString &input) {
    static CityData cityData = loadCityData();

    // 预处理输入（去除前缀/后缀）
    QString processed = processInput(input);

    if (cityData.cityToPinyin.contains(processed)) {
        return processed; // 返回拼音（根据需求可改为返回中文）
    }

    QRegularExpression re("^[a-zA-Z\\s]+$");
    if (re.match(input).hasMatch()) {
        QString lowerInput = input.toLower();

        if (cityData.pinyinToCity.contains(lowerInput)) {
            return cityData.pinyinToCity[lowerInput];
        }
        // 其他英文直接返回
        return input;
    }

    return QString();
}

QString CityConverter::processInput(const QString &input)
{
    QString result = input.trimmed();

    // 定义带有效性检查的正则表达式
    static const QRegularExpression prefixRegex(
        "^((?:中国|中华人民共和国|\\w+省|\\w+自治区|\\w+市))?"
        "[:：\\s-]*"
        "([\\x{4e00}-\\x{9fa5}]+)",
        QRegularExpression::UseUnicodePropertiesOption
        );

    if (!prefixRegex.isValid()) {
        qCritical() << "正则表达式初始化失败:"
                    << prefixRegex.errorString()
                    << "Pattern:" << prefixRegex.pattern();
        return result;
    }

    // 执行匹配
    QRegularExpressionMatch match = prefixRegex.match(result);
    if (match.hasMatch()) {
        result = match.captured(2); // 获取第二个捕获组
    }

    // 移除行政后缀
    static const QVector<QString> suffixes = {
        "市", "县", "区", "地区", "新区", "特别行政区"
    };
    for (const auto& suffix : suffixes) {
        if (result.endsWith(suffix)) {
            result.chop(suffix.length());
            break; // 找到第一个匹配后缀即退出
        }
    }

    return result;
}
